import React, { useEffect, useState } from 'react';
import { RouteComponentProps } from 'react-router-dom';
import moment from 'moment';
import { Spin, Tag, Card } from 'antd';
import './index.css';
import RecentList from '../../components/RecentList';

interface IRouteInfo {
  id: string;
}

interface IProps extends RouteComponentProps<IRouteInfo> {}

// 初始化文章
const initialTopic: ITopic = {
  id: '001',
  author_id: '002',
  content: '<p>null</p>',
  tab: 'all',
  title: 'null',
  reply_count: 0,
  visit_count: 0,
  top: false,
  good: false,
  last_reply_at: Date.now().toString(),
  create_at: Date.now().toString(),
  author: {
    loginname: 'string',
    avatar_url: 'string',
  },
};

// 初始化正文
const initialReplies: IReply[] = [
  {
    id: '003',
    author: {
      loginname: 'string',
      avatar_url: 'string',
    },
    content: '<p>reply</p>',
    ups: ['004'],
    create_at: Date.now().toString(),
    reply_id: '005',
    is_uped: false,
  },
];

// 初始化作者信息
const initialUser: IUser = {
  loginname: 'string',
  avatar_url: 'string',
  githubUsername: 'string',
  create_at: Date.now().toString(),
  score: 0,
  recent_topics: [
    {
      id: '009',
      author: {
        loginname: 'string',
        avatar_url: 'string',
      },
      title: 'string',
      last_reply_at: Date.now().toString(),
    },
  ],
  recent_replies: [
    {
      id: '010',
      author: {
        loginname: 'string',
        avatar_url: 'string',
      },
      title: 'string',
      last_reply_at: Date.now().toString(),
    },
  ],
};
const tabType = new Map([
  ['share', '分享'],
  ['ask', '问答'],
  ['job', '招聘'],
]);

const Detail: React.FunctionComponent<IProps> = (props) => {
  // 文章主要信息
  const [topic, setTopic] = useState<ITopic>(initialTopic);
  // 评论
  const [replies, setReplies] = useState<IReply[]>(initialReplies);
  // 作者信息
  const [author, setAuthor] = useState<IUser>(initialUser);

  const { id } = props.match.params;

  useEffect(() => {
    getTopic();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [id]);

  useEffect(() => {
    getRecentTopics(topic.author.loginname);
  }, [topic]);

  // 获取文章
  const getTopic = async () => {
    const response = await fetch(`https://cnodejs.org/api/v1/topic/${id}`);
    const { data } = await response.json();
    setReplies(data.replies);
    setTopic(data);
  };

  // 获取作者最近文章
  const getRecentTopics = async (author: string) => {
    if (author === initialUser.loginname) {
      return;
    }
    const response = await fetch(`https://cnodejs.org/api/v1/user/${author}`);
    const { data } = await response.json();
    setAuthor(data);
  };

  return (
    <div className="detail">
      <main>
        {/* 加载文章 */}
        {topic === initialTopic ? (
          <Spin className="loading" />
        ) : (
          <>
            <div className="title">
              {topic.top ? (
                <Tag className="tag" color="green">
                  置顶
                </Tag>
              ) : topic.good ? (
                <Tag className="tag" color="green">
                  精华
                </Tag>
              ) : (
                <Tag className="tag">{tabType.get(topic.tab) as string}</Tag>
              )}
              <h1 className="title-content">{topic.title}</h1>
              <p className="topic-info">
                <span>
                  发布时间：{moment(topic.create_at).format('YYYY-MM-DD')}
                </span>
                <span>{topic.visit_count}次浏览</span>
              </p>
            </div>
            <div
              className="content"
              dangerouslySetInnerHTML={{ __html: topic.content }}
            ></div>
          </>
        )}
        {/* 加载评论 */}
        {replies === initialReplies ? (
          <Spin className="loading" />
        ) : (
          <div className="replies">
            <h2>评论</h2>
            <ul>
              {replies.map((item, index) => {
                return (
                  <li key={item.id} className="replies-item">
                    <div className="user-info">
                      <img
                        src={item.author.avatar_url}
                        alt={item.author.loginname}
                      />
                    </div>
                    <div className="text-info">
                      <span className="name">
                        <span>{index + 1}楼</span>
                        <a href="///">{item.author.loginname}</a>
                        <span>
                          {moment(item.create_at).format('YYYY-MM-DD')}
                        </span>
                      </span>
                      <div
                        className="content"
                        dangerouslySetInnerHTML={{ __html: item.content }}
                      ></div>
                    </div>
                  </li>
                );
              })}
            </ul>
          </div>
        )}
      </main>
      <aside>
        <Card title="作者" className="author">
          <img src={topic.author.avatar_url} alt={topic.author.loginname} />
          <p className="author-name">
            <a href="///">{topic.author.loginname}</a>
          </p>
        </Card>
        <Card title="最近文章" className="recent-topic-card">
          <RecentList {...author} />
        </Card>
      </aside>
    </div>
  );
};

export default Detail;
